<template>
  <el-card class="box-card">
    <el-button type="primary" size="default" icon="Plus" @click="addTrademark">
      添加品牌
    </el-button>
    <el-table :data="trademarkArr" style="width: 100%; margin: 10px 0px" border>
      <el-table-column
        prop="id"
        label="序号"
        width="80"
        align="center"
        type="index"
      />
      <el-table-column prop="tmName" label="品牌名称" align="center" />
      <el-table-column label="品牌LOGO" align="center">
        <!-- 自定义插槽 -->
        <template #="{ row, column, $index }">
          <img
            :src="row.logoUrl"
            alt="糟糕图片找不到了。。。"
            style="width: 100px; height: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作" width="120" align="center">
        <!-- 自定义插槽 -->
        <template #="{ row, column, $index }">
          <el-button
            size="small"
            type="warning"
            icon="Edit"
            @click="updateTrademark(row)"
          />
          <el-popconfirm
            :title="`您确定要删除${row.tmName}吗？`"
            width="200px"
            icon="Delete"
            @confirm="removeTradeMark(row.id)"
          >
            <!-- popconfirm 自定义插槽 -->
            <template #reference>
              <el-button size="small" type="danger" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 pager-count:5~21的奇数-->
    <el-pagination
      :pager-count="5"
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[3, 5, 7, 9]"
      layout="prev, pager, next, jumper,->, sizes,total"
      :total="total"
      background="background"
      @current-change="getHasTrademark"
      @size-change="sizeChange"
    />
  </el-card>
  <el-dialog
    v-model="dialogVisible"
    :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
  >
    <el-form
      style="width: 80%"
      :model="trademarkParams"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input
          placeholder="请输入品牌名称"
          v-model="trademarkParams.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <!-- action 路径需要带上/api -->
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          v-model="trademarkParams.logoUrl"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTradeMark,
} from '@/api/product/trademark/index'
import {
  TradeMark,
  type Records,
  type TradeMarkResponseData,
} from '@/api/product/trademark/type'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
let pageNo = ref<number>(1)
let limit = ref<number>(3)
let total = ref<number>(0)
let trademarkArr = ref<Records>([])
const dialogVisible = ref<boolean>(false)
// 定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
// 表单校验实例
let formRef = ref()
const addTrademark = () => {
  dialogVisible.value = true
  // 打开弹框时时清空数据
  // 添加品牌之前可能修改品牌携带了ID数据；所以ID也需要清空
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  // 清空表单上一次错误提示信息；此时dom未渲染出dialog(undefined)
  // 两种写法 ES6 问号写法, fromRef存在就清楚校验提示
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
  nextTick(() => {
    formRef.value?.clearValidate('tmName')
    formRef.value?.clearValidate('logoUrl')
  })
}
const updateTrademark = (row: TradeMark) => {
  // 清除上一次的校验提示信息
  nextTick(() => {
    formRef.value?.clearValidate('tmName')
    formRef.value?.clearValidate('logoUrl')
  })
  dialogVisible.value = true
  // 更新要携带ID
  // ES6语法 合并对象
  Object.assign(trademarkParams, row)
  // trademarkParams.id = row.id
  // trademarkParams.tmName = row.tmName
  // trademarkParams.logoUrl = row.logoUrl
}
const getHasTrademark = async (pager = 1) => {
  // pager = 1 : 当前每一页的数据量发生变化的时候,当前页码归一
  pageNo.value = pager
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  )
  if (result.code == 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('Logo picture must be JPG|PNG|GIF format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('Logo picture size can not exceed 2MB!')
    return false
  }
  return true
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  // blob:http://localhost:5173/19445586-d14c-4235-9743-b9efa91cc5bb
  // console.log('--->', URL.createObjectURL(uploadFile.raw!))
  trademarkParams.logoUrl = response.data
  // 清除校验提示信息 clearValidate 清理某个字段的校验信息
  formRef.value.clearValidate('logoUrl')
}
onMounted(() => {
  getHasTrademark()
})

const sizeChange = () => {
  getHasTrademark()
}

const cancel = () => {
  dialogVisible.value = false
}

const confirm = async () => {
  // 发请求之前要对整个表单进行校验(包含logoUrl)
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  if (result.code == 200) {
    // 关闭对话框
    dialogVisible.value = false
    // 弹出提示信息
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    // 刷新列表：修改留在当前页，添加刷新到第一页
    getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    // 添加品牌失败
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
    // 关闭对话框
    dialogVisible.value = false
  }
}
// 品牌名称自定义校验
const validateTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length < 2) {
    callback(new Error('品牌名称位数大于等于两位'))
  } else {
    callback()
  }
}
// 品牌LOGO自定义校验
const validateLogoUrl = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('请上传品牌LOGO图片'))
  }
}
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validateTmName }],
  // 上传的trigger无效，提交表单的时候会触发校验方法
  logoUrl: [{ required: true, validator: validateLogoUrl }],
}
// 气泡确认框回调函数
const removeTradeMark = async (id: number) => {
  let result: any = await reqDeleteTradeMark(id)
  console.log('delete result==>', result)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    // 获取删除后的列表
    getHasTrademark(
      // 当前页条数大于1,传递当前页码，否则传递上一页的页码
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
